"""
redis操作封装类
用法：
    rs = RedisTool()
    # 写数据
    rs.set(key, value, ex=expireSeconds)
    # 读数据
    v = rs.get(key)
"""
import redis
from app.config import Config


class RedisTool:
    def __init__(self):
        self.redis = redis.Redis(**Config.get_redis_options())

    def set(self, key, content, expire=0):
        if expire > 0:
            return self.redis.set(key, content, ex=expire)
        else:
            return self.redis.set(key, content)

    def get(self, name):
        return self.redis.get(name)

    def close(self):
        self.redis.close()

def get_redis():
    rd = RedisTool()
    try:
        yield rd
    finally:
        rd.close()